package edu.uwosh.cs342.placestobe;


import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity{
	protected EditText usernameET;
	protected EditText passwordET;
	private static String userID;
	String password;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		Button loginButton = (Button) findViewById(R.id.enterPassword);
		loginButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				//check for valid info
				usernameET = (EditText) findViewById(R.id.userNameEditText);
				passwordET = (EditText) findViewById(R.id.passwordEditText);
				userID = usernameET.getText().toString();
				password = passwordET.getText().toString();
				try{
					new AsyncCheckServer().execute((Object[]) null);
				}catch(Exception e){
					Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater blowUp = getMenuInflater();
		blowUp.inflate(R.menu.login_menu, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.new_user:
			Intent myIntent = new Intent("android.intent.action.NEWUSER");
			startActivity(myIntent);
			break;
		}
		return false;
	}
	
	
	public static String getCurUser(){
		return userID;
	}
	
	private class AsyncCheckServer extends AsyncTask<Object, Object, Object>{
		String res = "";
		
		@Override
		protected Object doInBackground(Object... params) {
			String response = null;  
			try {  
				res= CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/authenticateUser.php?user="+userID+"&pass="+password); 
				res=res.toString().trim();    
			} catch (Exception e) {  }
			return null;
		}
		@Override
		protected void onPostExecute(Object result){
			if(res.equalsIgnoreCase("1") ){
				go();				
			}else{
				Toast.makeText(getApplicationContext(), "Login unsuccessful", Toast.LENGTH_SHORT).show();
				System.out.println(res);
			}
		}
	}
	
	private void go(){
		MainActivity.setUserID(userID);
		Intent myIntent = new Intent("android.intent.action.MAP");
		startActivity(myIntent);
	}
		

	
}
